<?php

namespace app\api\controller;

use app\api\model\DtsGame;
use app\api\services\DtsService;
use think\facade\Cache;
use think\worker\Server;
use Workerman\Lib\Timer;

class WebSocket extends Server
{
    protected $socket = 'http://0.0.0.0:8084';

    protected $redis;

    public function onWorkerStart($worker)
    {
        Timer::add(1, function () use ($worker) {
            foreach ($worker->connections as $connection) {
                if (isset($connection->uid) && $connection->uid) {
                    $msg = $this->refreshData($connection->uid);
                    if ($msg) {
                        $connection->send($msg);
                    }
                }
            }
        });
    }

    public function onWebSocketConnect($connection, $httpBuffer)
    {
        $uid = $this->decodeToken($_GET['token']);
        if (!$uid) {
            $connection->send(json_encode(['code' => 0, 'message' => 'no auth']));
        } else {
            $connection->uid = $uid;
        }
    }


    public function onConnect($connection)
    {
    }

    public function onClose($connection)
    {
        foreach ($connection->worker->connections as $con) {
            $con->send(json_encode(['code' => 1, 'message' => 'success', 'data' => ['action' => 'exit_room', 'uid' => $connection->uid ?? 0]]));
        }
    }

    public function onMessage($connection, $data)
    {
        $message = json_decode($data);
        if (!$message) {
            return;
        }
        switch ($message->action) {
            case 'login':
                $token = $message->data->token ?? '';
                $uid = $this->decodeToken($token);
                if (!$uid) {
                    $connection->send(json_encode(['code' => 0, 'message' => 'no auth']));
                } else {
                    $connection->send(json_encode(['code' => 1, 'message' => 'login success']));
                    $connection->uid = $uid;
                }
                break;
            case 'checkout':

                break;
        }
    }

    public function refreshData($uid)
    {
        $game_id = Cache::store("redis")->get('game_dts_last_game_id');

        $game = DtsGame::find($game_id);
        if (!$game) {
            return '';
        }
        $timer = $game->end_time - time();
        //房间人数限制
        $max_people = DtsService::$max_people;
        $user_list = DtsService::getGameUserList($game);
        $join_people = DtsService::getGameUserBettingList($user_list);
        $gameData = DtsService::getUserGameData($game, $uid);

        $data = [
            'user_id'             => $uid,
            'period'             => $game_id,
            'beginTime'          => $game->start_time ?? 0, //开始时间
            'endTime'            => $game->end_time ?? 0, //结束时间
            'gameStatus'               => $game->state,// 状态：1:进行中 2:开始倒计时 3:结束
            'timer'               => max($timer, 0), // 剩余秒数
            'attackIndex'         => $game->killer_room, // 本期去的房间
            'pre_killer_room'     => $game->pre_killer_room,//上期去的房间
            'userCount'         => count($join_people), // 加入的人
            'max_people'          => $max_people, // 最大人数
            'total_killer_amount' => $game->total_killer_amount, //杀手去的房间总投注
            'user_bonus'          => $gameData->bonus ?? 0, //
            'user_amount'         => $gameData->amount ?? 0, //
            'userList'           => $user_list, // 用户列表
            'roomMap'           => DtsService::calcRoomAmount($user_list), // 用户列表
            'timestamp'           => time()
        ];

        return json_encode($data);
    }

    protected function decodeToken(string $token)
    {
        try {
            $jwt = new \Jwt();
            $uid = $jwt->verifyToken($token);
//            $uid = app(JwtAuthLib::class)->decode($token)->data;
//            $uid = (int)$jwt->uid;
        } catch (\Exception $exception) {
            return 0;
        }
        return $uid;
    }

}